package com.sixth.controller;

import com.sixth.bean.MarketUser;
import com.sixth.bean.bo.WxAuthRegisterBo;
import com.sixth.bean.bo.WxAuthResetBo;
import com.sixth.bean.common.BaseRespVo;
import com.sixth.bean.common.BaseResultVo;
import com.sixth.bean.common.WxInfoBean;
import com.sixth.bean.common.WxUserBeanOfWxInfoBean;
import com.sixth.constant.Constant;
import com.sixth.service.WxAuthService;
import com.sixth.shiro.MarketToken;
import com.sixth.util.EncryptionUtil;
import com.sixth.util.MarketInfoUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName WxAuthController
 * @Description TODO
 * @Author XiaoWJ
 * @Date 2022/9/10 21:03
 **/

@RestController
@RequestMapping("wx/auth")
public class WxAuthController {

    @Autowired
    WxAuthService wxAuthService;

    /**
     * 用户登录
     *
     * @Param map, session
     * @Return BaseRespVo
     * @author XiaoWJ
     * @date 2022/9/11 22:15
     */

    @RequestMapping("login")
    public BaseRespVo login(@RequestBody Map map, HttpServletRequest req) {

        String username = (String) map.get("username");
        String password = (String) map.get("password");

        // 登录的时候不需要加密，shiro帮忙做了
        //String password = EncryptionUtil.getMD5String((String) map.get("password"),username);

        Subject subject = SecurityUtils.getSubject();

        // 构造认证令牌
        MarketToken marketToken = new MarketToken(username, password, Constant.WX_LOGIN);

        // 进行登录认证
        subject.login(marketToken);


        // 从subject中获取身份信息返回出去
        MarketUser marketUser = MarketInfoUtil.getMarketUser();

        // 认证成功，更新最近一次登录时间和最近一次登录ip
        wxAuthService.updateIPAndLoginTime(marketUser.getId(), req.getRemoteAddr());

        WxUserBeanOfWxInfoBean wxUserBeanOfWxInfoBean = new WxUserBeanOfWxInfoBean(marketUser.getNickname(), marketUser.getAvatar());

        String token = (String) subject.getSession().getId();

        WxInfoBean wxInfoBean = new WxInfoBean(wxUserBeanOfWxInfoBean, token);

        // 设置session的存活时间
        HttpSession session = req.getSession();
        session.setMaxInactiveInterval(120 * 60);

        return BaseRespVo.ok(wxInfoBean);
    }

    /**
     * 用户退出登录
     *
     * @Param
     * @Return
     * @author XiaoWJ
     * @date 2022/9/11 22:15
     */

    @RequestMapping("logout")
    public BaseResultVo logout() {

        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseResultVo.ok();

    }


    /**
     * 验证手机号格式是否正确
     *
     * @Param
     * @Return
     * @author XiaoWJ
     * @date 2022/9/11 22:16
     */

    @RequestMapping("regCaptcha")
    public BaseResultVo regCaptcha(@RequestBody Map map) {
        String mobile = (String) map.get("mobile");
        String pattern = "^(13[0-9]|14[0-9]|15[0-9]|166|17[0-9]|18[0-9]|19[8|9])\\d{8}$";

        if (mobile.trim().matches(pattern)) {
            return BaseResultVo.ok();
        }

        return new BaseResultVo(402, "手机格式不匹配!");

    }

    /**
     * 用户注册
     *
     * @Param
     * @Return
     * @author XiaoWJ
     * @date 2022/9/11 22:58
     */

    @RequestMapping("register")
    public Object register(@RequestBody WxAuthRegisterBo wxAuthRegisterBo, HttpServletRequest request) {
        // 判断验证码是否正确
        if (!Constant.INVALIDATE_CODE.equals(wxAuthRegisterBo.getCode().trim())) {
            return BaseResultVo.error("验证码错误");
        }
        // 用于自动登录使用
        String pwd = wxAuthRegisterBo.getPassword();

        // 数据库中存储加密后的密码
        String password = EncryptionUtil.getMD5String(wxAuthRegisterBo.getPassword(),wxAuthRegisterBo.getUsername());

        wxAuthRegisterBo.setPassword(password);

        int code = wxAuthService.register(wxAuthRegisterBo);

        if (code == Constant.NON) {
            return BaseResultVo.error("注册失败");
        } else if (code == Constant.REGISTER_ERROR_USERNAME_EXIST) {
            return new BaseResultVo(Constant.REGISTER_ERROR_USERNAME_EXIST,
                    "用户名已存在");
        } else if (code == Constant.REGISTER_ERROR_MOBILE_EXIST) {
            return new BaseResultVo(Constant.REGISTER_ERROR_MOBILE_EXIST,
                    "手机号已注册");
        }
        // 注册成功，自动登录

        HashMap<String, Object> map = new HashMap<>();
        map.put("username", wxAuthRegisterBo.getUsername());
        map.put("password", pwd);

        return login(map, request);

    }

    /**
     * @Param
     * @Return
     * @author XiaoWJ
     * @date 2022/9/12 10:32
     */

    @RequestMapping("reset")
    public BaseResultVo reset(@RequestBody WxAuthResetBo wxAuthResetBo) {
        // 判断验证码是否正确

        if (!Constant.INVALIDATE_CODE.equals(wxAuthResetBo.getCode().trim())) {
            return new BaseResultVo(703, "验证码错误");
        }

        // 密码加密
        //wxAuthResetBo.setPassword(EncryptionUtil.getMD5String(wxAuthResetBo.getPassword()));

        int code = wxAuthService.reset(wxAuthResetBo);

        if (code == Constant.NON) {
            return BaseResultVo.error("手机号未注册");
        }

        return BaseResultVo.ok();
    }


}
